package controllers

import (
	"encoding/json"
	"strconv"
	"supershare/backend/models"

	"github.com/beego/beego/v2/server/web"
)

// MemberLevelController 会员等级控制器
type MemberLevelController struct {
	web.Controller
}

// List 获取会员等级列表
func (c *MemberLevelController) List() {
	// 检查权限
	permResult := CheckControllerPermission(c.Ctx)
	if !permResult.Success {
		RespondWithError(&c.Controller, permResult)
		return
	}

	// 获取分页参数
	page, _ := c.GetInt("page", 1)
	pageSize, _ := c.GetInt("pageSize", 10)

	// 获取过滤参数
	filters := make(map[string]interface{})
	name := c.GetString("name")
	if name != "" {
		filters["name"] = name
	}

	status, err := c.GetInt8("status")
	if err == nil {
		filters["status"] = status
	}

	// 加盟商管理员只能查看自己加盟商的数据
	if permResult.Admin.FranchiseId > 0 {
		filters["franchise_id"] = permResult.Admin.FranchiseId
	}

	// 获取会员等级列表
	levels, total, err := models.GetMemberLevelList(page, pageSize, filters)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "获取会员等级列表失败: " + err.Error(),
		}
		c.ServeJSON()
		return
	}

	// 返回结果
	c.Data["json"] = map[string]interface{}{
		"success": true,
		"data": map[string]interface{}{
			"list":  levels,
			"total": total,
		},
	}
	c.ServeJSON()
}

// GetOne 获取单个会员等级详情
func (c *MemberLevelController) GetOne() {
	// 检查权限
	permResult := CheckControllerPermission(c.Ctx)
	if !permResult.Success {
		RespondWithError(&c.Controller, permResult)
		return
	}

	// 获取ID参数
	idStr := c.Ctx.Input.Param(":id")
	id, err := strconv.ParseInt(idStr, 10, 64)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "无效的会员等级ID",
		}
		c.ServeJSON()
		return
	}

	// 获取会员等级信息
	level, err := models.GetMemberLevelById(id, permResult.Admin.FranchiseId)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "获取会员等级信息失败: " + err.Error(),
		}
		c.ServeJSON()
		return
	}

	// 返回结果
	c.Data["json"] = map[string]interface{}{
		"success": true,
		"data":    level,
	}
	c.ServeJSON()
}

// Create 创建会员等级
func (c *MemberLevelController) Create() {
	// 检查权限
	permResult := CheckControllerPermission(c.Ctx)
	if !permResult.Success {
		RespondWithError(&c.Controller, permResult)
		return
	}

	// 解析请求数据
	var level models.MemberLevel
	err := json.Unmarshal(c.Ctx.Input.RequestBody, &level)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "无效的请求数据: " + err.Error(),
		}
		c.ServeJSON()
		return
	}

	// 设置加盟商ID
	level.FranchiseId = permResult.Admin.FranchiseId
	level.BeforeInsert()

	// 创建会员等级
	id, err := models.CreateMemberLevel(&level)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "创建会员等级失败: " + err.Error(),
		}
		c.ServeJSON()
		return
	}

	// 返回结果
	c.Data["json"] = map[string]interface{}{
		"success": true,
		"message": "创建会员等级成功",
		"data": map[string]interface{}{
			"id": id,
		},
	}
	c.ServeJSON()
}

// Update 更新会员等级
func (c *MemberLevelController) Update() {
	// 检查权限
	permResult := CheckControllerPermission(c.Ctx)
	if !permResult.Success {
		RespondWithError(&c.Controller, permResult)
		return
	}

	// 获取ID参数
	idStr := c.Ctx.Input.Param(":id")
	id, err := strconv.ParseInt(idStr, 10, 64)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "无效的会员等级ID",
		}
		c.ServeJSON()
		return
	}

	// 获取会员等级信息
	existingLevel, err := models.GetMemberLevelById(id, permResult.Admin.FranchiseId)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "获取会员等级信息失败: " + err.Error(),
		}
		c.ServeJSON()
		return
	}

	// 解析请求数据
	var level models.MemberLevel
	err = json.Unmarshal(c.Ctx.Input.RequestBody, &level)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "无效的请求数据: " + err.Error(),
		}
		c.ServeJSON()
		return
	}

	// 设置ID和加盟商ID
	level.Id = id
	level.FranchiseId = existingLevel.FranchiseId
	level.BeforeUpdate()

	// 更新会员等级
	err = models.UpdateMemberLevel(&level, permResult.Admin.FranchiseId, "Code", "Name", "Icon", "Description", "Discount", "PointsLimit", "PointRate", "Status", "SortOrder", "Benefits", "UpdatedAt", "UpdatedBy")
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "更新会员等级失败: " + err.Error(),
		}
		c.ServeJSON()
		return
	}

	// 返回结果
	c.Data["json"] = map[string]interface{}{
		"success": true,
		"message": "更新会员等级成功",
	}
	c.ServeJSON()
}

// Delete 删除会员等级
func (c *MemberLevelController) Delete() {
	// 检查权限
	permResult := CheckControllerPermission(c.Ctx)
	if !permResult.Success {
		RespondWithError(&c.Controller, permResult)
		return
	}

	// 获取ID参数
	idStr := c.Ctx.Input.Param(":id")
	id, err := strconv.ParseInt(idStr, 10, 64)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "无效的会员等级ID",
		}
		c.ServeJSON()
		return
	}

	// 检查是否有会员使用该等级
	memberCount, err := models.GetMemberCountByLevelId(id, permResult.Admin.FranchiseId)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "检查会员数量失败: " + err.Error(),
		}
		c.ServeJSON()
		return
	}

	if memberCount > 0 {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "该会员等级下有会员，无法删除",
		}
		c.ServeJSON()
		return
	}

	// 删除会员等级
	err = models.DeleteMemberLevel(id, permResult.Admin.FranchiseId)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "删除会员等级失败: " + err.Error(),
		}
		c.ServeJSON()
		return
	}

	// 返回结果
	c.Data["json"] = map[string]interface{}{
		"success": true,
		"message": "删除会员等级成功",
	}
	c.ServeJSON()
}

// GetAll 获取所有激活的会员等级
func (c *MemberLevelController) GetAll() {
	// 检查权限
	permResult := CheckControllerPermission(c.Ctx)
	if !permResult.Success {
		RespondWithError(&c.Controller, permResult)
		return
	}

	// 获取所有激活的会员等级
	levels, err := models.GetAllActiveMemberLevels(permResult.Admin.FranchiseId)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "获取会员等级列表失败: " + err.Error(),
		}
		c.ServeJSON()
		return
	}

	// 返回结果
	c.Data["json"] = map[string]interface{}{
		"success": true,
		"data": map[string]interface{}{
			"list": levels,
		},
	}
	c.ServeJSON()
}
